import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store';
Vue.use(VueRouter)

// import Layout from '../layout/Index.vue'
import dataDisplayRouter from './modules/dataDisplay'
import systemManagementRouter from './modules/systemManagement'
import storeManagementRoute from './modules/storeManagement'
import commodityManagementRoute from './modules/commodityManagement'
import orderManagementRoute from './modules/orderManagement'
import paymentManagementRoute from './modules/paymentManagement'
import errorRouter from './modules/error'
const routes = [
  {
    path: '/',
    redirect: '/dataDisplay'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue')
  },
  dataDisplayRouter,
  systemManagementRouter,
  storeManagementRoute,
  commodityManagementRoute,
  orderManagementRoute,
  paymentManagementRoute,
  errorRouter,
  { path: '/consoleOrderDetails', component:()=>import('@/views/ConsoleOrderDetails.vue') },
  { path: '*', redirect: '/error', hidden: true }
]

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})
const originalPush = VueRouter.prototype.push
 
VueRouter.prototype.push = function push(location) {
  // console.log(location)
  return originalPush.call(this, location).catch(err => err)
}
const whiteList = ['/login']// no redirect whitelist
router.beforeEach((to, from, next) => {
  const hasToken = store.state.user.token
  if(hasToken){
    if(to.path == '/login'){
      next({ path: '/' })
    }else{
      if(store.state.menu.init === false){
        store.dispatch('menu/GetMenu').then(()=>{
          next({...to,replace:true})
        })
      }else{
        next()
      }
    }
  }else{
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next({ path: '/login' }) // 否则全部重定向到登录页
    }
  }
})
export default router
